const mysql  = require('mysql2/promise');
const {connection} = require('./common');

//获取数据
async function getHotel(){
    let sql = 'select * from pub'
    let res = await connection.execute(sql);
    return JSON.stringify(res[0]);
}
//增加数据
async function addHotel(data){
    let obj = data;
    let str = '';
    let arr = []
    for(let i in obj){
      if(i == 'upload'){
        arr.push('pubImg')
        if(obj[i].length == 1){
          str = str + `'${obj[i][0].response.addr}',`
        }else{
          let str0 = '';
          for(let j = 0 ; j< obj[i].length;j++){
            str0 = str0 + `${obj[i][j].response.addr};`
          }
          str = str + `'${str0}'`
        }
        
      }else{
        arr.push(i)
        str = str + `'${obj[i]}',`
      }
    }
    let x = str.slice(0,str.length-1);
    let sql = `INSERT INTO pub(${arr}) VALUES (${x})`
    await connection.execute(sql); 
    return JSON.stringify("success");
}
//删除数据
async function deleteHotel(data){
    let obj = data;
    let pubID = obj.pubID;
    let cityID = obj.cityID;
    let sql = `DELETE FROM pub WHERE pubID = '${pubID}' and cityID = '${cityID}'`
    await connection.execute(sql); 
    return JSON.stringify("success");
}
//更改数据
async function putHotel(data){
    let result = data;
    let newObj = result.new;
    let id0 = result.old.pubID;
    let id1 = result.old.cityID;
    let str = '';
    for(let i in newObj){
      str = str + `${i} = '${newObj[i]}',`
    }
    let x = str.slice(0,str.length-1);
    let sql = `UPDATE pub SET ${x} WHERE pubID = '${id0}' and cityID = '${id1}'`
    let res = await connection.execute(sql)
    return JSON.stringify('success!')
}

module.exports = {
    getHotel,
    addHotel,
    deleteHotel,
    putHotel
}